package org.example.springtest.service.impl;
import org.example.springtest.model.entity.User;
import org.example.springtest.repository.UserRepository;
import org.example.springtest.service.RedisService;
import org.example.springtest.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.springtest.model.dto.user.LoginResponse;

import java.util.HashMap;
import java.util.Objects;

@Service
public class UserServiceImpl implements org.example.springtest.service.UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RedisService redisService;
    @Override
    public LoginResponse login(String loginAccount, String loginPassword) {
        LoginResponse response = new LoginResponse();
        User user = userRepository.findByLoginAccountAndLoginPassword(loginAccount, loginPassword);
        if(Objects.nonNull(user)){
            String token =  JwtUtil.generateToken(user.getUserName(),user.getId().toString());
            HashMap<String, Integer> expirationData = JwtUtil.getExpiration() ;
            BeanUtils.copyProperties(user,response);
            response.setToken(token);
            redisService.addUser(response,expirationData.get("hour"));
        }
        return response ;
    }

    @Override
    public boolean loginOut(String userId) {
        boolean isDelete =  redisService.delete(userId);
          return isDelete;
    }
}
